import { join } from 'path';

// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';

export default class extends think.Controller {
  /**
   * @desc 预约系统
   * @return {Promise} []
   */
  // 提交预约信息
  async postAppointmentOrderAction() {
    const order = this.post();
    // 时间戳
    order.timestamp = Math.floor(new Date(order.date + ' ' + order.time).getTime() / 1000);
    order.addtime = Math.floor(new Date().getTime() / 1000);
    // 查询该时间点是否被选择
    const isExist = await this.model('or_appointment').where({userid: order.userid, date: order.date, timepoint: order.timepoint}).find();
    if (!think.isEmpty(isExist)) {
      return this.fail('该时间段已被预约！');
    }
    const res = await this.model('or_appointment').add(order);
    return res ? this.success(res) : this.fail('操作失败');
  }

  // 获取单个订单信息
  async getAppointmentOrderAction() {
    const id = this.get().id;
    // 获取信息
    const order = await this.model('or_appointment')
      .alias('a')
      .field('a.*, u.name as uname, s.name as sname, u.headurl, u.username')
      .join('think_or_app_user u on a.userid = u.id')
      .join('think_or_subject s on a.subjectid = s.id')
      .where({'a.id': id})
      .find();
    return this.json(order);
  }

  // 获取员工的指定一天的剩余时间点
  async getUserDayLeftPointAction() {
    const filter = this.get();
    const res = await this.model('or_appointment')
      .where({userid: filter.userid, date: filter.date})
      .getField('timepoint');
    const userPoint = Array.from(new Array(48).keys());
    return this.json(this.removeList(userPoint, res));
  }

  // 去除前面数组中在后面数组存在的数据
  removeList(a, b) {
    return a.filter(index => b.indexOf(index) === -1);
  }
}
